home *** CD-ROM | disk | FTP | other *** search
- Newsgroups: comp.lang.c++
- Path: in2.uu.net!allegra!alice!ark
- From: ark@research.att.com (Andrew Koenig)
- Subject: Re: downcast with virtual base class - illegal but why
- Message-ID: <Dpyp25.EDq@research.att.com>
- Organization: AT&T Research, Murray Hill NJ
- References: <31741697.7881@zurich.ibm.com>
- Date: Tue, 16 Apr 1996 15:44:29 GMT
-
- In article <31741697.7881@zurich.ibm.com> Keith Whittingham <wgk@zurich.ibm.com> writes:
-
- > I know the downcast from a virtual base class is illegal but why?
-
- Because there may be more than one derived class subobject of the
- same object with the same type and the same virtual base class object.
- In that case, there is no way to tell which of the derived class
- subobjects was intended. For example:
-
- class V { };
-
- class B: public virtual V { };
-
- class D: public B { }
-
- class E: public B, public D { };
-
- Every object of class E now contains a B part and a D part.
- The D part contains a(nother) B part. Each B part refers to the
- same V object. So suppose we have:
-
- V* vp;
-
- B* bp = (B*) vp;
-
- where vp really points at the V part of an E object. The cast is
- ambiguous -- there is no way to tell which B was intended.
-
- Now, you may agree that this example should be illegal because
- the ambiguity is obvious. But suppose we deleted the definitions
- of classes D and E. Wouldn't that remove the ambiguity?
-
- Unfortunately, it wouldn't. For example, the definitions of D
- and E might have moved to a different translation unit entirely.
- Their mere existence in that translation unit renders the cast
- in this one ambiguous. That means that in general there is no way
- to determine at compile time whether any cast from a virtual base
- class to a derived class is ambiguous; C++ therefore prohibits
- them all.
- --
- --Andrew Koenig
- ark@research.att.com
-